<template>
    <div id="mapContainer" class="map-container" />
</template>

<script>
// import Vue from 'vue'
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'

export default {
    name: 'LeafletMapView',

    // props: {
    //     basin: String,
    // },

    data() {
        return {
            icon: L.icon({
                // iconUrl: encodeURI(`',
                iconUrl: 'data:image/svg+xml,' + encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100px" height="100px"><circle cx="50" cy="50" r="40" stroke="#F8F8F8" stroke-width="10" fill="#444" /></svg>`),
                iconSize: [12, 12],
                iconAnchor: [6, 6]
            }),
            watamLayer: L.geoJSON([], {
                style: function (f) {
                    return {
                        color: '#E07516',
                        weight: 2,
                        fill: !0,
                        opacity: 0.7,
                        fillColor: '#ffffff00',
                        fillOpacity: 0
                    }
                }
            }),
            rivlLayer: L.geoJSON([], {
                style: function (f) {
                    var d = f.properties
                    return {
                        color: '#4FC1FF',
                        weight: 1 + Number(d.RVLEVEL) / 2,
                        opacity: 0.7
                        // fill: !0,
                        // fillColor: '#ffffff00',
                        // fillOpacity: 0
                    }
                }
            }),
            tipLayer: L.layerGroup()
        }
    },

    computed: {
        // 流域编码
        basin() {
            return this.$route.query.basin
        }
    },
    watch: {
        basin: {
            handler: function (name) {
                this.$nextTick(() => {
                    this.getData()
                })
            },
            immediate: true
        }
    },

    created() {
        this.markerList = []
    },

    mounted() {
        this.init()
    },

    methods: {
        init() {
            this.mapL = L.map('mapContainer', {
                //
                center: [19.134063385426998, 110.07083391999744],
                zoom: 8,
                zoomSnap: 0.1,
                // 放大、缩小地图时的 zoom 最小变化粒度，默认值 1
                zoomDelta: 0.2,
                // 不添加属性说明控件
                attributionControl: false,
                // 禁用 + - 按钮
                zoomControl: false,
                // 禁用双击放大
                doubleClickZoom: false
            })
            L.tileLayer('http://t{s}.tianditu.gov.cn/DataServer?tk={tk}&T={type}_{crs}&X={x}&Y={y}&L={z}', {
                subdomains: '01234567'.split(''),
                type: 'img', // vec:矢量底图  img:影像底图  ter:地形底图  cva:矢量注记  cia:影像注记  cta:地形注记
                // 默认使用经纬度坐标系
                crs: 'w', // c：EPSG:4326   W：EPSG3857
                // 默认的授权密钥
                tk: '49c334b7f61e855209b846bde9f67e4a',
                // 展示边界
                // bounds: [
                //   [-90, -180],
                //   [90, 180],
                // ],
                // noWrap: !0,
                // tms: !0,
                // tileSize: 256.5,
                zoomOffset: 0 // crs=c：1  crs=w：0
            }).addTo(this.mapL)
            // L.tileLayer('http://{s}.tianditu.gov.cn/DataServer?tk={tk}&T={type}_{crs}&X={x}&Y={y}&L={z}', {
            //     subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
            //     type: 'cva', // vec:矢量底图  img:影像底图  ter:地形底图  cva:矢量注记  cia:影像注记  cta:地形注记
            //     // 默认使用经纬度坐标系
            //     crs: 'w', // c：EPSG:4326   W：EPSG3857
            //     // 默认的授权密钥
            //     tk: '49c334b7f61e855209b846bde9f67e4a',
            //     // 展示边界
            //     // bounds: [
            //     //   [-90, -180],
            //     //   [90, 180],
            //     // ],
            //     // noWrap: !0,
            //     zoomOffset: 0 // crs=c：1  crs=w：0
            // }).addTo(this.mapL)

            // 功能图层添加进地图
            this.watamLayer.addTo(this.mapL)
            this.rivlLayer.addTo(this.mapL)
            this.tipLayer.addTo(this.mapL)
            this.mapL.on('zoomend', this.mapZoomendEvent)
            this.mapL.options.zoomSnap = 0.1
        },
        fitBounds(bounds) {
            try {
                var b = this.formatBoundsToAry(bounds)

                this.mapL.options.zoomSnap = 0.1
                this.mapL.fitBounds(b, {
                    animate: !0
                })
                this.mapL.options.zoomSnap = 1
            } catch (error) {
                console.info('ERR:', b, this.mapL, error)
            }
        },
        lnglatAryTolatlngAry(data) {
            if (typeof data[0] === 'object') {
                return data.map(this.lnglatAryTolatlngAry)
            } else if (typeof data[0] === 'number' && data.length === 2) {
                return [data[1], data[0]]
            } else {
                return [0, 0]
            }
        },
        formatBoundsToAry(b) {
            if (b && b[0] && b[0][0]) {
                return [...b]
            }
            if (b._southWest && b._northEast) {
                return [[b._southWest.lat, b._southWest.lng], [b._northEast.lat, b._northEast.lng]]
            }
            return [[0, 0], [0, 0]]
        },
        clearLayer() {
            console.log('clear on here...')
            this.watamLayer.clearLayers()
            this.rivlLayer.clearLayers()
            this.tipLayer.clearLayers()
            this.markerList = []
        },
        mapZoomendEvent(evt) {
            const z = this.mapL.getZoom()
            this.markerList.forEach((d) => {
                if (d.z <= z && !d.tag) {
                    d.m.addTo(this.tipLayer)
                    d.tm.addTo(this.tipLayer)
                    d.tag = !0
                } else if (d.z > z && d.tag) {
                    d.m.remove()
                    d.tm.remove()
                    d.tag = !1
                }
            })
        },
        // 初始化村庄以及注记
        initTip(data) {
            data.filter((d) => (d.LGTD !== null && d.LTTD !== null))
                .forEach((d) => {
                    // const marker = L.circleMarker([d.LTTD, d.LGTD], {
                    //     radius: 4,
                    //     color: '#f8f8f8',
                    //     weight: 1.5,
                    //     fill: !0,
                    //     fillColor: '#444',
                    //     fillOpacity: 1,
                    // })
                    const marker = L.marker([d.LTTD, d.LGTD], {
                        icon: this.icon
                    })
                    if (d.ADCD.endsWith('000000') || d.ADNM.endsWith('镇')) {
                        const tm = L.marker([d.LTTD, d.LGTD], {
                            icon: L.divIcon({
                                className: '',
                                html: `<div style="white-space: nowrap;margin: -15px 0 0 15px;font-size: 16px;color: white;">${d.ADNM}</div>`
                            })
                        })
                        this.markerList.push({ tag: !1, z: 0, m: marker, tm: tm })
                    } else if (d.ADCD.endsWith('000') && d.ADNM.endsWith('村')) {
                        const tm = L.marker([d.LTTD, d.LGTD], {
                            icon: L.divIcon({
                                className: '',
                                html: `<div style="white-space: nowrap;margin: -12px 0 0 15px;font-size: 14px;color: white;">${d.ADNM}</div>`
                            })
                        })
                        this.markerList.push({ tag: !1, z: 12.6, m: marker, tm: tm })
                    } else {
                        const tm = L.marker([d.LTTD, d.LGTD], {
                            icon: L.divIcon({
                                className: '',
                                html: `<div style="white-space: nowrap;margin: -10px 0 0 15px;font-size: 12px;color: white;">${d.ADNM}</div>`
                            })
                        })
                        this.markerList.push({ tag: !1, z: 16, m: marker, tm: tm })
                    }
                })
        },
        /**
         * 获取数据
         */
        getData() {
            this.clearLayer()
            // 获取数据
            var getWatam = this.$axios.get(`${mapConfig.resUrlPre}/geojson/${this.basin}/WATAM.json`)
            var getRivl = this.$axios.get(`${mapConfig.resUrlPre}/geojson/${this.basin}/RIVL.json`)
            var getFZC = this.$axios.get(`${mapConfig.resUrlPre}/geojson/${this.basin}/FZC.json`)
            Promise.all([getWatam, getRivl, getFZC]).then(([watam, rivl, fzc]) => {
                this.watamLayer.addData(watam.data.features)
                this.rivlLayer.addData(rivl.data.features)
                this.initTip(fzc.data.features.map((d) => ({
                    ADCD: d.properties.ADCD,
                    ADNM: d.properties.ADNM,
                    LGTD: d.properties.LGTD,
                    LTTD: d.properties.LTTD
                })))
                this.fitBounds(this.watamLayer.getBounds())
            })
        }
    }
}
</script>

<style lang="scss" >
.map-container {
    width: 100%;
    height: 100%;
    background-color: white;
    z-index: 1;
    overflow: hidden;
}
</style>
